<template>
	<view class="content">
		<view class="header">
			<text class="title">Data Input</text>
		</view>
		
		<view class="tabs">
			<view class="tab" :class="{ 'active': activeTab === 'rgb' }" @click="activeTab = 'rgb'">
				RGB Input
			</view>
			<view class="tab" :class="{ 'active': activeTab === 'concentration' }" @click="activeTab = 'concentration'">
				Data Management
			</view>
		</view>
		
		<!-- RGB输入页面 -->
		<view class="tab-content" v-if="activeTab === 'rgb'">
			<view class="input-section">
				<view class="input-row global-ion-type-row">
					<text class="section-title ion-type-label">Current Ion Type:</text>
					<input type="text" v-model="globalIonType" placeholder="e.g., Fe³⁺ (Required)" class="global-ion-input"/>
				</view>
				<text class="input-tip ion-type-tip">All subsequent data points will use this ion type.</text>

				<view class="base-rgb-section">
					<text class="section-title">Baseline RGB Input (Concentration=0)</text>
					<view class="input-row">
						<input type="number" v-model="baseRgbData.r" placeholder="Baseline R" />
						<input type="number" v-model="baseRgbData.g" placeholder="Baseline G" />
						<input type="number" v-model="baseRgbData.b" placeholder="Baseline B" />
						<button @click="addBaseRgbData" type="primary">Add Baseline RGB</button>
					</view>
					<text class="input-tip">Baseline RGB values (at concentration 0) are used for (S₀-S)/S₀ calculation.</text>
				</view>
				
				<view class="input-row">
					<input type="number" v-model="rgbData.r" placeholder="R Value" />
					<input type="number" v-model="rgbData.g" placeholder="G Value" />
					<input type="number" v-model="rgbData.b" placeholder="B Value" />
					<button @click="addRgbData" type="primary">Add RGB</button>
				</view>
				<text class="input-tip">Ensure the current ion type is set above.</text>

				<view class="batch-input-section">
					<text class="section-title">Batch Data Input</text>
					<textarea class="batch-textarea" v-model="batchRgbInput" placeholder="Supported formats (uses the global ion type set above):
1. R,G,B,Concentration (e.g., 88,155,239,0.2)
2. R,G,B (Concentration defaults to null, set in Data Management)
3. RGB xx xx xx
4. R,G,B,0 (Adds as baseline RGB, concentration 0)
One data set per line." :maxlength="-1"></textarea>
					<button @click="addBatchRgbData" type="primary">Batch Add</button>
				</view>
			</view>
		</view>
		
		<!-- 数据管理页面 -->
		<view class="tab-content" v-if="activeTab === 'concentration'">
			<view class="data-management-section">
				<view v-if="globalIonType" class="current-ion-type-display">
				  <text>Currently Analyzing Ion Type: {{ globalIonType }}</text>
				</view>
				<view class="management-actions">
					<button type="warn" size="mini" @click="batchDeleteMode = !batchDeleteMode">
						{{ batchDeleteMode ? 'Cancel Batch' : 'Batch Delete' }}
					</button>
					<button v-if="batchDeleteMode" type="default" size="mini" @click="toggleSelectAll">
						{{ isAllSelected ? 'Deselect All' : 'Select All' }}
					</button>
					<button v-if="batchDeleteMode" type="warn" size="mini" @click="deleteSelected" :disabled="!hasSelectedItems">
						Delete Selected
					</button>
				</view>
				
				<view v-if="completeData.length === 0" class="empty-notice">
					<text>No Data</text>
				</view>
				
				<view v-else>
					<view class="input-group" v-for="(point, index) in completeData" :key="index">
						<text class="data-group-index">ID: {{ index + 1 }}</text>
						<view class="data-row">
							<checkbox v-if="batchDeleteMode" :checked="selectedItems.includes(index)" @click="toggleSelect(index)" class="checkbox" />
							<view class="input-cell">
								<text class="input-label">R:</text>
								<input type="number" v-model="completeData[index].r" class="editable-input" />
							</view>
							<view class="input-cell">
								<text class="input-label">G:</text>
								<input type="number" v-model="completeData[index].g" class="editable-input" />
							</view>
							<view class="input-cell">
								<text class="input-label">B:</text>
								<input type="number" v-model="completeData[index].b" class="editable-input" />
							</view>
							<view class="color-preview" :style="{ backgroundColor: `rgb(${point.r}, ${point.g}, ${point.b})` }"></view>
						</view>
						<view class="data-row">
							<view class="input-cell concentration-cell">
								<text class="input-label">Concentration:</text>
								<input type="number" v-model="completeData[index].concentration" class="editable-input" />
							</view>
							<view class="input-cell error-cell">
								<text class="input-label">Error ±:</text>
								<input type="number" v-model="completeData[index].error" class="editable-input" />
							</view>
							<text v-if="!batchDeleteMode" class="delete-btn" @click="removeCompleteData(index)">Delete</text>
							<text v-if="!batchDeleteMode" class="edit" @click="editCompleteData(index)">Edit</text>
						</view>
					</view>
					
					<view class="action-buttons">
						<button class="batch-delete-btn" type="warn" @click="clearAllData">Clear All</button>
						<button @click="exportData" type="default">Export Data</button>
						<button @click="goToAnalysis" type="primary" :disabled="completeData.length < 2">Start Analysis</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				activeTab: 'rgb',
				globalIonType: '',
				rgbData: {
					r: '',
					g: '',
					b: ''
				},
				baseRgbData: {
					r: '',
					g: '',
					b: ''
				},
				incompleteData: [],  // 仅有RGB数据但没有浓度
				completeData: [],    // 完整的数据
				batchRgbInput: '',
				isRgbTableCollapsed: false,
				concentrationInputs: [], // 用于存储浓度输入
				batchDeleteMode: false,
				selectedItems: [],
				isAllSelected: false
			}
		},
		computed: {
			hasSelectedItems() {
				return this.selectedItems.length > 0;
			}
		},
		watch: {
			// 监听数据变化，自动保存
			completeData: {
				handler() {
					this.saveToStorage();
				},
				deep: true
			}
		},
		onLoad() {
			// 从存储中恢复数据
			try {
				const complete = uni.getStorageSync('completeData');
				
				if (complete) {
					this.completeData = JSON.parse(complete);
					if (this.completeData.length > 0 && this.completeData[0].ionType) {
					    this.globalIonType = this.completeData[0].ionType;
					}
				}
			} catch (e) {
				console.error('Failed to load stored data', e);
			}
		},
		methods: {
			// 添加基准RGB数据（浓度为0）
			addBaseRgbData() {
				if (!this.globalIonType || !this.globalIonType.trim()) {
					uni.showToast({
						title: 'Please set the current ion type above.',
						icon: 'none'
					});
					return;
				}
				// 验证输入
				if (!this.baseRgbData.r || !this.baseRgbData.g || !this.baseRgbData.b) {
					uni.showToast({
						title: 'Please enter complete baseline RGB values.',
						icon: 'none'
					});
					return;
				}
				
				this.completeData.push({
					r: Number(this.baseRgbData.r),
					g: Number(this.baseRgbData.g),
					b: Number(this.baseRgbData.b),
					ionType: this.globalIonType.trim(),
					concentration: 0,
					error: null,
					timestamp: Date.now()
				});
				
				this.saveToStorage();
				this.baseRgbData = { r: '', g: '', b: '' };
				this.activeTab = 'concentration';
				uni.showToast({
					title: 'Baseline RGB data added.',
					icon: 'success'
				});
			},
			
			// 添加单组RGB数据
			addRgbData() {
				if (!this.globalIonType || !this.globalIonType.trim()) {
					uni.showToast({
						title: 'Please set the current ion type above.',
						icon: 'none'
					});
					return;
				}
				// 验证输入
				if (!this.rgbData.r || !this.rgbData.g || !this.rgbData.b) {
					uni.showToast({
						title: 'Please enter complete RGB values.',
						icon: 'none'
					});
					return;
				}
				
				this.completeData.push({
					r: Number(this.rgbData.r),
					g: Number(this.rgbData.g),
					b: Number(this.rgbData.b),
					ionType: this.globalIonType.trim(),
					concentration: null,
					error: null,
					timestamp: Date.now()
				});
				
				this.saveToStorage();
				this.rgbData = { r: '', g: '', b: '' };
				this.activeTab = 'concentration';
				uni.showToast({
					title: 'RGB data added. Please set concentration values.',
					icon: 'success',
					duration: 2500
				});
			},
			
			// 初始化浓度输入数组
			initConcentrationInputs() {
				// 确保concentrationInputs数组长度与incompleteData一致
				const currentLength = this.concentrationInputs.length;
				const requiredLength = this.incompleteData.length;
				
				if (currentLength < requiredLength) {
					// 添加新的输入项
					for (let i = currentLength; i < requiredLength; i++) {
						this.concentrationInputs.push({
							value: '',
							error: ''
						});
					}
				} else if (currentLength > requiredLength) {
					// 移除多余的输入项
					this.concentrationInputs.splice(requiredLength);
				}
			},
			
			// 批量添加RGB数据
			addBatchRgbData() {
				if (!this.globalIonType || !this.globalIonType.trim()) {
					uni.showToast({
						title: 'Please set the current ion type above.',
						icon: 'none'
					});
					return;
				}
				if (!this.batchRgbInput.trim()) {
					uni.showToast({
						title: 'Please enter batch RGB data.',
						icon: 'none'
					});
					return;
				}
				
				const text = this.batchRgbInput;
				let addedCount = 0;
				let baseRgbCount = 0;
				let failedCount = 0;
				
				const lines = text.trim().split('\n');
				for (const line of lines) {
					const values = line.trim().split(',').map(v => v.trim());
					
					// CSV格式: R,G,B,浓度  或者 R,G,B
					if (values.length >= 3) { // 至少需要R,G,B
						const r = parseInt(values[0]);
						const g = parseInt(values[1]);
						const b = parseInt(values[2]);
						let concentration = null;

						if (values.length === 4) { // R,G,B,浓度
							if (!isNaN(parseFloat(values[3]))) {
								concentration = parseFloat(values[3]);
							}
						} // 如果只有R,G,B，浓度保持null

						if (!isNaN(r) && !isNaN(g) && !isNaN(b)) {
							this.completeData.push({
								r, g, b,
								concentration,
								ionType: this.globalIonType.trim(),
								error: null,
								timestamp: Date.now()
							});
							if (concentration === 0) baseRgbCount++;
							else addedCount++;
						} else {
							failedCount++;
						}
					} else {
						// 尝试解析 "RGB xx xx xx" 格式
						const rgbParts = line.trim().match(/^RGB\s+(\d+)\s+(\d+)\s+(\d+)$/i);
						if (rgbParts && rgbParts.length === 4) {
							const r = parseInt(rgbParts[1]);
							const g = parseInt(rgbParts[2]);
							const b = parseInt(rgbParts[3]);
							if (!isNaN(r) && !isNaN(g) && !isNaN(b)) {
								this.completeData.push({
									r, g, b,
									concentration: null, // RGB格式默认浓度为null
									ionType: this.globalIonType.trim(),
									error: null,
									timestamp: Date.now()
								});
								addedCount++;
							} else {
								failedCount++;
							}
						} else {
							failedCount++;
						}
					}
				}
				
				const totalAdded = addedCount + baseRgbCount;
				if (totalAdded > 0) {
					this.saveToStorage();
					this.batchRgbInput = '';
					this.activeTab = 'concentration';
					
					let message = '';
					if (baseRgbCount > 0) message += `Added ${baseRgbCount} baseline data sets. `;
					if (addedCount > 0) message += `Added ${addedCount} regular data sets. `;
					if (failedCount > 0) message += `${failedCount} lines had incorrect format and were not added. `;
					else message += 'Please check and set concentrations.'

					uni.showToast({
						title: message.trim(),
						icon: 'none',
						duration: 3000
					});
				} else {
					uni.showToast({
						title: 'No valid data found. Please check the format.',
						icon: 'none',
						duration: 3000
					});
				}
			},
			
			// 删除完整数据
			removeCompleteData(index) {
				this.completeData.splice(index, 1);
				this.saveToStorage();
			},
			
			// 切换选择单个项目
			toggleSelect(index) {
				const position = this.selectedItems.indexOf(index);
				if (position > -1) {
					this.selectedItems.splice(position, 1);
				} else {
					this.selectedItems.push(index);
				}
				this.isAllSelected = this.selectedItems.length === this.completeData.length;
			},
			
			// 切换全选
			toggleSelectAll() {
				if (this.isAllSelected) {
					this.selectedItems = [];
					this.isAllSelected = false;
				} else {
					this.selectedItems = this.completeData.map((_, index) => index);
					this.isAllSelected = true;
				}
			},
			
			// 删除选中项
			deleteSelected() {
				if (this.selectedItems.length === 0) return;
				
				uni.showModal({
					title: 'Confirm Deletion',
					content: `Are you sure you want to delete the selected ${this.selectedItems.length} items?`,
					success: (res) => {
						if (res.confirm) {
							// 从高到低排序索引，这样删除时不会影响其他索引
							const sortedIndexes = [...this.selectedItems].sort((a, b) => b - a);
							
							// 删除选中的项
							sortedIndexes.forEach(index => {
								this.completeData.splice(index, 1);
							});
							
							this.saveToStorage();
							this.selectedItems = [];
							this.isAllSelected = false;
							
							uni.showToast({
								title: 'Selected data deleted.',
								icon: 'success'
							});
						}
					}
				});
			},
			
			// 保存数据到本地存储
			saveToStorage() {
				try {
					uni.setStorageSync('completeData', JSON.stringify(this.completeData));
				} catch (e) {
					console.error('Failed to save data', e);
				}
			},
			
			// 导出数据
			exportData() {
				const csvData = ['R,G,B,Concentration,IonType,Error'];
				
				this.completeData.forEach(point => {
					csvData.push(`${point.r},${point.g},${point.b},${point.concentration !== null ? point.concentration : ''},${point.ionType || ''},${point.error || ''}`);
				});
				
				const csvString = csvData.join('\n');
				
				// 复制到剪贴板
				uni.setClipboardData({
					data: csvString,
					success: () => {
						uni.showToast({
							title: 'Data copied to clipboard.',
							icon: 'success'
						});
					}
				});
			},
			
			// 跳转到分析页面
			goToAnalysis() {
				if (!this.globalIonType || !this.globalIonType.trim()) {
					uni.showToast({
						title: 'Please set the current ion type for analysis first.',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				const invalidConcentrationPoints = this.completeData.filter(point => point.concentration === null || point.concentration === undefined);
				if (invalidConcentrationPoints.length > 0) {
					uni.showToast({
						title: `${invalidConcentrationPoints.length} data points have no concentration set.`,
						icon: 'none',
						duration: 2500
					});
					return;
				}
				
				this.saveToStorage();
				
				let xAxisLabel = `Concentration of ${this.globalIonType.trim()} (μM)`;

				uni.navigateTo({
					url: `/pages/analysis/analysis?xAxisLabel=${encodeURIComponent(xAxisLabel)}`
				});
			},
			
			// 清空所有数据
			clearAllData() {
				uni.showModal({
					title: 'Confirm Clear',
					content: 'Are you sure you want to clear all data?',
					success: (res) => {
						if (res.confirm) {
							this.completeData = [];
							this.saveToStorage();
							
							uni.showToast({
								title: 'All data cleared.',
								icon: 'success'
							});
						}
					}
				});
			},
			
			// 编辑完整数据
			editCompleteData(index) {
				const dataToEdit = { ...this.completeData[index] };
				// this.incompleteData.push(dataToEdit); // Logic for incompleteData might need review if still used
				// this.initConcentrationInputs(); 

				this.rgbData = {
					r: dataToEdit.r,
					g: dataToEdit.g,
					b: dataToEdit.b
					// ionType is global, not set on rgbData during edit
				};
				// The globalIonType remains as is. If user saves this edit,
				// the existing addRgbData or similar logic would apply the current globalIonType.

				// For now, simply remove from completeData and prompt user to manage/re-add if needed
				// or directly edit in the concentration tab.
				this.completeData.splice(index, 1); 
				this.activeTab = 'concentration'; 

				uni.showToast({
					title: 'Data populated to RGB input area above (ion type is the current global setting). Please edit concentration in Data Management or re-add.',
					icon: 'none',
					duration: 3500
				});
			}
		}
	}
</script>

<style>
	.content {
		padding: 20rpx;
	}
	
	.header {
		text-align: center;
		margin-bottom: 30rpx;
	}
	
	.title {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
	}
	
	.tabs {
		display: flex;
		border-bottom: 1px solid #ddd;
		margin-bottom: 20rpx;
	}
	
	.tab {
		flex: 1;
		text-align: center;
		padding: 15rpx 0;
		font-size: 28rpx;
		color: #666;
	}
	
	.tab.active {
		color: #007AFF;
		border-bottom: 2px solid #007AFF;
	}
	
	.input-section {
		margin-bottom: 30rpx;
		background-color: #f5f5f5;
		padding: 20rpx;
		border-radius: 10rpx;
	}
	
	.input-row {
		display: flex;
		flex-direction: row;
		margin-bottom: 20rpx;
	}
	
	.input-row input {
		flex: 1;
		margin-right: 10rpx;
		height: 70rpx;
		border: 1px solid #ddd;
		border-radius: 6rpx;
		padding: 0 10rpx;
		background-color: #fff;
	}
	
	.data-table {
		margin-bottom: 30rpx;
		border: 1px solid #eee;
		border-radius: 10rpx;
		overflow: hidden;
	}
	
	.table-header {
		display: flex;
		background-color: #f0f0f0;
		font-weight: bold;
	}
	
	.table-row {
		display: flex;
		border-top: 1px solid #eee;
	}
	
	.table-cell {
		flex: 1;
		padding: 15rpx;
		text-align: center;
	}
	
	.table-count {
		padding: 10rpx 15rpx;
		background-color: #f8f8f8;
		font-size: 24rpx;
		color: #666;
		border-bottom: 1px solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.table-actions {
		display: flex;
		gap: 10rpx;
	}
	
	.action-btn {
		color: #2196F3;
		font-size: 24rpx;
		padding: 5rpx 10rpx;
		border: 1px solid #2196F3;
		border-radius: 6rpx;
	}
	
	.delete {
		color: #dd524d;
	}
	
	.edit {
		color: #007aff;
		margin-left: 10px;
	}
	
	.batch-input-section {
		margin-top: 30rpx;
	}
	
	.section-title {
		font-weight: bold;
		margin-bottom: 15rpx;
		display: block;
	}
	
	.batch-textarea {
		width: 100%;
		height: 200rpx;
		border: 1px solid #ddd;
		border-radius: 6rpx;
		padding: 10rpx;
		margin-bottom: 15rpx;
		background-color: #fff;
	}
	
	.empty-notice {
		padding: 50rpx 0;
		text-align: center;
		color: #999;
		font-size: 30rpx;
	}
	
	.data-management-section {
		background-color: #f5f5f5;
		padding: 20rpx;
		border-radius: 10rpx;
		margin-bottom: 30rpx;
	}
	
	.management-actions {
		display: flex;
		gap: 10rpx;
		margin-bottom: 20rpx;
	}
	
	.input-group {
		background-color: #fff;
		padding: 15rpx;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
		display: flex;
		flex-direction: column;
		border: 1px solid #eee;
		gap: 10rpx;
	}
	
	.data-row {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 10rpx;
	}
	
	.input-cell {
		display: flex;
		align-items: center;
		flex: 1;
		min-width: 150rpx;
	}
	
	.input-label {
		font-size: 24rpx;
		color: #666;
		margin-right: 10rpx;
		white-space: nowrap;
	}
	
	.editable-input {
		flex: 1;
		height: 60rpx;
		border: 1px solid #ddd;
		border-radius: 6rpx;
		padding: 0 10rpx;
		font-size: 26rpx;
	}
	
	.concentration-cell {
		flex: 2;
	}
	
	.error-cell {
		flex: 2;
	}
	
	.color-preview {
		width: 50rpx;
		height: 50rpx;
		border-radius: 8rpx;
		border: 1px solid #ddd;
		flex-shrink: 0;
	}
	
	.delete-btn {
		color: #dd524d;
		font-size: 24rpx;
		white-space: nowrap;
	}
	
	.action-buttons {
		display: flex;
		gap: 20rpx;
		margin-top: 20rpx;
	}
	
	.action-buttons button {
		flex: 1;
	}
	
	.checkbox {
		margin-right: 10rpx;
	}
	
	.batch-delete-btn {
		background-color: #dd524d;
		color: #fff;
		border: none;
		padding: 10rpx 20rpx;
		border-radius: 6rpx;
		font-size: 28rpx;
	}
	
	.input-tip {
		display: block;
		font-size: 24rpx;
		color: #666;
		margin-top: 5rpx;
		margin-bottom: 15rpx; /* 为单个RGB输入和批量输入之间增加间距 */
	}
	
	.global-ion-type-row {
		margin-bottom: 5rpx !important; /* 减少全局离子输入行下方的间距 */
	}

	.ion-type-label {
		white-space: nowrap;
		margin-right: 10rpx;
		font-weight: bold;
		font-size: 28rpx;
	}
	.global-ion-input {
		flex: 1;
		height: 70rpx;
		border: 1px solid #ddd;
		border-radius: 6rpx;
		padding: 0 10rpx;
		background-color: #fff;
	}

	.ion-type-tip {
		margin-bottom: 25rpx !important; /* 增加离子类型提示下方的间距 */
		font-size: 24rpx;
		color: #666;
		display: block;
	}
	
	.current-ion-type-display {
		padding: 10rpx;
		background-color: #e0f0ff;
		border-radius: 6rpx;
		margin-bottom: 15rpx;
		text-align: center;
		font-size: 26rpx;
		color: #333;
	}

	.data-group-index {
		font-weight: bold;
		margin-bottom: 10rpx;
		display: block;
		color: #333;
		font-size: 28rpx;
	}
</style> 